<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="js/marked.min.js"></script>
    <link rel="stylesheet" href="css/style.css">

    <title></title>

</head>
<body>
<div class="chat-container">
    <div class="right-panel">
        <div id="chat-box" class="chat-box"></div>
        <form id="form" class="input-form">
            <input type="text" id="message" name="message" placeholder="请输入您要提问的信息!">
            <input type="submit" value="发送">
            <div id="loader" class="loader" style="display: none;"></div>
        </form>
    </div>
</div>
<script>
    var loader = document.getElementById("loader");

    document.getElementById("form").addEventListener("submit", function (event) {
        event.preventDefault();

        var messageInput = document.getElementById("message");
        var message = messageInput.value;
        messageInput.value = "";

        var chatBox = document.getElementById("chat-box");

        var userMessage = document.createElement("div");
        userMessage.className = "message user-message";
        userMessage.textContent = "您: " + message;
        chatBox.appendChild(userMessage);
        chatBox.scrollTop = chatBox.scrollHeight;

        loader.style.display = "block";

        var xhr = new XMLHttpRequest();
        xhr.open("GET", "http://localhost:8080/ai/stream?message=" + encodeURIComponent(message), true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                loader.style.display = "none";

                if (xhr.status === 200) {
                    var response = xhr.responseText;

                    var botMessage = document.createElement("div");
                    botMessage.className = "message bot-message";

                    var botMessageText = document.createElement("span");
                    botMessageText.className = "message-text";
                    botMessage.appendChild(botMessageText);
                    botMessageText.innerHTML = marked.marked(response);

                    chatBox.appendChild(botMessage);
                    chatBox.scrollTop = chatBox.scrollHeight;
                }
            }
        };

        xhr.onloadstart = function () {
            loader.style.display = "block";
        };

        xhr.onloadend = function () {
            loader.style.display = "none";
        };

        xhr.send();
    });

</script>
</body>
</html>
